import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, PageHeader, Divider, Badge } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import SearchForm from './SearchFormDetails';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class ProductionOrder_details extends Component {
	state = {
		dataSource: [],
		visible: false,
		advanced: false,
		searchItem: {},
		pageSize: 10,
		pageNum: 1,
		total: 40,
		statesList: [
			{ id: 0, value: '新建' },
			{ id: 1, value: '已派工' },
			{ id: 2, value: '已开工' },
			{ id: 3, value: '已报工' },
			{ id: 9, value: '删除' },
		],
		materialStatusList: [
			{ id: 0, value: '正常' },
			{ id: 1, value: '欠料' },
		],
		columns: [
			{
				title: '序号',
				dataIndex: 'id',
				width: 50,
				align: 'center',
				render: (text, record, index) => `${index + 1}`,
			},

			{
				title: '物料编码',
				width: 150,
				dataIndex: 'partCode',
				sorter: (a, b) => compareString(a.partCode, b.partCode)
			},
			{
				title: '图号',
				width: 150,
				// allowEllipsis: true,
				dataIndex: 'paperCode',
				sorter: (a, b) => compareString(a.paperCode, b.paperCode)
			},
			{
				title: '物料名称',
				width: 150,
				dataIndex: 'partName',
				sorter: (a, b) => compareString(a.partName, b.partName)
			},
			{
				title: '物料规格',
				width: 150,
				dataIndex: 'partSpec',
				sorter: (a, b) => compareString(a.partSpec, b.partSpec)
			},
			{
				title: '数量',
				width: 100,
				dataIndex: 'partNeedNum',
				sorter: (a, b) => compareNum(a.partNeedNum, b.partNeedNum),
			},
			{
				title: '领料',
				width: 100,
				dataIndex: 'partReceivedNum',
				sorter: (a, b) => compareNum(a.partReceivedNum, b.partReceivedNum),
			},
			{
				title: '发料',
				width: 100,
				dataIndex: 'grantNum',
				sorter: (a, b) => compareNum(a.grantNum, b.grantNum),
			},
			{
				title: '收料',
				width: 100,
				dataIndex: 'receiveNum',
				sorter: (a, b) => compareNum(a.receiveNum, b.receiveNum),
			},
			{
				title: '欠料',
				width: 100,
				dataIndex: 'materialStatus',
				sorter: (a, b) => compareNum(a.materialStatus, b.materialStatus),
				render: (text) => {
					let a = this.state.materialStatusList.find(item => item.id == text)
					return a.id == '0' ? <span style={{ color: '#1e8e3e' }}>{a.value}</span>
						: a.id == '1' ? <span style={{ color: '#ff0000' }}>{a.value}</span> : a.value
				}
			},
			{
				title: '仓库',
				width: 100,
				dataIndex: 'storeName',
				sorter: (a, b) => compareString(a.storeName, b.storeName),
			},
			{
				title: '装配班组',
				width: 150,
				dataIndex: 'groupName',
				sorter: (a, b) => compareString(a.groupName, b.groupName),
			}, 
			{
				title: '装配组别代码',
				width: 150,
				dataIndex: 'groupCode',
				sorter: (a, b) => compareString(a.groupCode, b.groupCode),
			},
			{
				title: '装配组别名称',
				width: 150,
				dataIndex: 'assemblyGroup',
				sorter: (a, b) => compareString(a.assemblyGroup, b.assemblyGroup),
			}, 
			{
				title: '状态',
				width: 100,
				dataIndex: 'isStates',
				sorter: (a, b) => compareString(a.isStates, b.isStates),
				render: (text) => {
					let a = this.state.statesList.find(item => item.id == text)
					return a.id == '0' ? <Badge status="default" text={<span style={{ color: '#d9d9d9' }}>{a.value}</span>} />
						: a.id == '2' ? <Badge status="warning" text={<span style={{ color: '#ffc440' }}>{a.value}</span>} />
							: a.id == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{a.value}</span>} />
								: a.id === '3' ? <Badge color='#1890ff' text={<span style={{ color: '#1890ff' }}>{a.value}</span>} /> : a.value
				}
			},
			{ dataIndex: '' }
		],
		fileList: [[], [], [], []],
		locationData: {},
		searchItemFather: {},
		loading: false,
		downloadLoading: false
	};
	componentDidMount() {
		console.log(this.props.location.data)
		this.setState({ locationData: this.props.location.data ? this.props.location.data.record : JSON.parse(localStorage.getItem('productionOrder_detailsList')), searchItemFather: this.props.location.data ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('productionOrder_searchItem')) }, this.fetch)
		// this.fetch();
	}
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	//初始化加载数据
	fetch = (pageNum = 1, pageSize = 100) => {
		this.setState({ loading: true });
		const { locationData, searchItem } = this.state;
		const data = { ...locationData, ...searchItem }
		data.pageNum = pageNum;
		data.pageSize = pageSize;
		// let str = ''
		// for (let key in data) {
		// 	if (data[key] || data[key] === 0) {
		// 		str += `&${key}=${data[key]}`
		// 	}
		// }
		console.log(data, 'data - fetch');
		ProductionOrderService.findPlanDetailsMaterial(data).then(res => {
			this.setState({ loading: false })
			if (res.data.code !== 200) {
				openModalMessage('warning', res.data.data.msg);
				return;
			}
			this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize });
		}).catch(err => {
			openModalMessage('error', err.message);
		})
	}


	handleSearch = value => {
		this.setState({ searchItem: value }, this.fetch);
	};

	onHandleAdvanced = () => {
		this.setState({ advanced: !this.state.advanced })
	}
	loadData = (value, dataSource) => {
		console.log(value, dataSource)
	}
	downloadFather = () => {
		const { dataSource } = this.state;
		this.setState({ downloadLoading: true });
		ProductionOrderService.exportProductionOrderManageDetailExcel({ dtoList: dataSource }).then(res => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('工序详情');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
			this.setState({ downloadLoading: false })
		})

	}

	resetForm = () => {
		this.formSearch && this.formSearch.resetFields();
		this.setState({ searchItem: {} }, this.fetch);
	}
	render() {
		const { locationData, loading, dataSource, advanced, columns, pageNum, pageSize, total, searchItemFather, searchItem, downloadLoading } = this.state;
		return (
			<div>
				<BasicLayoutSearch>
					<PageHeader
						style={{ padding: '4px 24px' }}
						onBack={() => this.props.history.push({ pathname: '/productionOrder', data: { searchItemFather, batchNo: locationData.batchNo } })}
						title={`${locationData.procedureName}工序详情`}>
					</PageHeader>
					<Divider />
					<SearchForm onSearch={this.handleSearch}
						onClick={this.onHandleAdvanced}
						advanced={advanced} searchItem={searchItem}
						resetForm={this.resetForm}
						ref={node => (this.formSearch = node)} />
				</BasicLayoutSearch>
				<BasicLayout buttons={[<Button key={2} onClick={this.downloadFather} loading={downloadLoading} type='primary' icon='download'>导出</Button>]} name={`${locationData.procedureName}工序详情`} icon="table">
					<TableCustomize
						columns={columns}
						rowKey={(record, index) => record.partCode + '_' + index}
						allowDrafting={true}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
					/>
					<BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
				</BasicLayout>

			</div>
		);
	}
}
export default Form.create()(withRouter(ProductionOrder_details));